package com.health.mapp.impl;

import com.health.db.dto.StuffDetailDto;
import com.health.db.model.*;
import com.health.db.service.msg.ImMsgNoticeService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.sm.IWXService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserCashAccountIdNoService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.*;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by YYY on 2017/5/31.
 */
public class BindWeChatAccountImpl implements ActionInterface {

    private IUserLISTService userLISTService;
    private IRongService rongService;
    private ImMsgNoticeService imMsgNoticeService;
    private IWXService wxService;
    private IUserCashAccountIdNoService userCashAccountIdNoService;
    private IStuffListService stuffListService;

    @Override
    public Response execute(Header header, Object reqBean) throws Exception {

        BindWeChatAccountReq req = (BindWeChatAccountReq) reqBean;
        //do it bobo
        BindWeChatAccountResp _resp = new BindWeChatAccountResp();


        if (StringUtils.isBlank(req.getUserPhone())||
                StringUtils.isBlank(req.getSmsCode()) ||
                StringUtils.isBlank(req.getWxToken()) ||
                StringUtils.isBlank(req.getRefreshToken()) ||
                null == req.getTag()) {

            _resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
            _resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
            return _resp;
        }

        /**
        ImMsgNoticeExample notice = new ImMsgNoticeExample();
        notice.setRandom(req.getSmsCode());
        notice.setNoticeReceiveAddress(req.getUserPhone());
        notice.setIsUsedFlag((short) 1);
        List<ImMsgNotice> list=imMsgNoticeService.selectByExample(notice);

        if (list.size()!=1) {
            _resp.setErrorCode(ResultCode.SMS_ERROR);
            _resp.setErrorMsg(ResultCode.SMS_ERROR_NOTE);
            return _resp;
        }
        imMsgNoticeService.updateForUserd(notice);
        **/

        UserLIST user = null;
        if (req.getTag() == 0) {
            user = userLISTService.selectByUserNo(req.getUserPhone());
        } else {
            StuffDetailDto stuffDetail = stuffListService.selectByStuffNo(req.getUserPhone());
            if (null!=stuffDetail)
            {
                user = userLISTService.selectByUserId(stuffDetail.getStuffid());
            }

        }

        if (null != user) {
            WXTokenModel tokenModel = null;
            if (null != user.getTypeid() && user.getTypeid() == 1) {
                tokenModel = wxService.refreshToken(req.getRefreshToken());
            } else {
                tokenModel = wxService.refreshDocToken(req.getRefreshToken());
            }
            if (null != tokenModel
                    && !TextUtils.isEmpty(tokenModel.getAccess_token())
                    && !TextUtils.isEmpty(tokenModel.getOpenid())) {

                List<UserLIST> userLISTS = userLISTService.selectByWXOpenid(tokenModel.getOpenid());
                if (null != userLISTS && userLISTS.size() > 0 && !userLISTS.get(0).getUserNo().equals(req.getUserPhone())) {
                    _resp.setErrorCode(-1);
                    _resp.setErrorMsg("该微信账户已绑定其他账号");
                    return _resp;
                } else {


                    /**
                     * 在用户表中绑定微信信息
                     * */
                    user.setWxopenid(tokenModel.getOpenid());
                    user.setUnionid(tokenModel.getUnionid());
                    userLISTService.updateByPrimaryKey(user);

                    /**
                     * 判断医生账户信息 如果没有微信账户则将微信登录的账户新增到账户列表中
                     * */
                    if (null!=req.getTag()&&req.getTag()==1)
                    {
                        List<UserLIST> userLISTs1=userLISTService.selectByWXOpenid(tokenModel.getOpenid());
                        if (null!=userLISTs1&&
                                userLISTs1.size()>0)
                        {
                            UserLIST userLIST=userLISTs1.get(0);
                            if (userLIST.getUserid().equals(user.getUserid()))
                            {
                                //检查医生账户信息 没有账户则新增微信账户为默认账户
                                UserCashAccountIdNoExample example=new UserCashAccountIdNoExample();
                                UserCashAccountIdNoExample.Criteria criteria=example.createCriteria();
                                criteria.andOwneridEqualTo(user.getUserid());
                                criteria.andAccounttypeidEqualTo(1);
                                criteria.andIsUsedFlagEqualTo((short) 1);
                                List<UserCashAccountIdNo> userCashAccountIdNos=userCashAccountIdNoService.queryUserCashAccountIdNo(example);
                                if (null==userCashAccountIdNos||userCashAccountIdNos.size()==0)
                                {

                                    WXUserInfo wxUserInfo=wxService.getWXUserInfo(tokenModel.getAccess_token(),tokenModel.getOpenid());
                                    Date now=new Date();
                                    UserCashAccountIdNo userCashAccountIdNo=new UserCashAccountIdNo();
                                    userCashAccountIdNo.setSystemid(0);
                                    userCashAccountIdNo.setOwnerid(user.getUserid());
                                    userCashAccountIdNo.setAccountBankName("微信");
                                    userCashAccountIdNo.setAccountIdno("weixin");
                                    userCashAccountIdNo.setAccountName(wxUserInfo.getNickname());
                                    userCashAccountIdNo.setAccountIdentityid(tokenModel.getOpenid());
                                    userCashAccountIdNo.setAccounttypeid(1);
                                    userCashAccountIdNo.setAccountTypeName("微信");
                                    userCashAccountIdNo.setContactPhone(user.getUserNo());
                                    userCashAccountIdNo.setIsUsedFlag((short) 1);
                                    userCashAccountIdNo.setCreateDate(now);
                                    userCashAccountIdNo.setUpdateDate(now);
                                    userCashAccountIdNo.setCreateUserid(user.getUserid());
                                    userCashAccountIdNo.setUpdateUserid(user.getUpdateUserid());
                                    userCashAccountIdNoService.insertUserCashAccountIdNo(userCashAccountIdNo);
                                }

                            }
                        }
                    }

                    _resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
                    _resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
                    return _resp;
                }

            } else {
                _resp.setErrorCode(-1);
                _resp.setErrorMsg("绑定历史用户失败");
                return _resp;
            }
        } else {
            _resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS);
            _resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS_NOTE);
            return _resp;
        }
    }

    public IUserLISTService getUserLISTService() {
        return userLISTService;
    }

    public void setUserLISTService(IUserLISTService userLISTService) {
        this.userLISTService = userLISTService;
    }

    public IRongService getRongService() {
        return rongService;
    }

    public void setRongService(IRongService rongService) {
        this.rongService = rongService;
    }

    public ImMsgNoticeService getImMsgNoticeService() {
        return imMsgNoticeService;
    }

    public void setImMsgNoticeService(ImMsgNoticeService imMsgNoticeService) {
        this.imMsgNoticeService = imMsgNoticeService;
    }

    public IWXService getWxService() {
        return wxService;
    }

    public void setWxService(IWXService wxService) {
        this.wxService = wxService;
    }

    public IUserCashAccountIdNoService getUserCashAccountIdNoService() {
        return userCashAccountIdNoService;
    }

    public void setUserCashAccountIdNoService(IUserCashAccountIdNoService userCashAccountIdNoService) {
        this.userCashAccountIdNoService = userCashAccountIdNoService;
    }

    public IStuffListService getStuffListService() {
        return stuffListService;
    }

    public void setStuffListService(IStuffListService stuffListService) {
        this.stuffListService = stuffListService;
    }


}
